package com.meantodo.demo.controller;

import com.meantodo.demo.data.UserRepository;
import com.meantodo.demo.domain.Goal;
import com.meantodo.demo.domain.User;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Author: tongqianwen
 * @Date: 2025/5/28
 */
@Slf4j
@Controller
@RequestMapping("/register")
public class RegistrationController {

    @Autowired
    UserRepository userRepository;

    @GetMapping
    public String showForm(Model model){
        model.addAttribute("user", new User());
        return "register";
    }
    // 处理注册请求
    @PostMapping
    public String registerUser(@Valid User user, BindingResult result, Model model) {
        // 检查是否有验证错误
        if (result.hasErrors()) {
            return "register";
        }

        // 这里可以添加业务逻辑，如检查用户名是否已存在等
        System.out.println(user);
        userRepository.save(user);

        // 模拟注册成功
        return "redirect:/register/success";
    }

    @RequestMapping("/success")
    @ResponseBody
    public String registerSuccess(){
        System.out.println(userRepository.findAll());
        return "register success ";
    }
}
